package com.kun.mall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.kun.common.to.mq.SeckillOrderTo;
import com.kun.common.utils.R;
import com.kun.common.vo.MemberRespVo;
import com.kun.mall.seckill.feign.CouponFeignService;
import com.kun.mall.seckill.feign.ProductFeignService;
import com.kun.mall.seckill.interceptor.LoginUserInterceptor;
import com.kun.mall.seckill.service.SeckillService;
import com.kun.mall.seckill.to.SecKillSkuRedisTo;
import com.kun.mall.seckill.vo.SeckillSesssionsWithSkus;
import com.kun.mall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author fangkun
 * @create 2023-04-11-10:30
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSku() {
        //扫描最近三天参与秒杀的活动
        R r = couponFeignService.getLatest3Session();
        if (r.getCode() == 0){
            List<SeckillSesssionsWithSkus> sesssions = r.getData(new TypeReference<List<SeckillSesssionsWithSkus>>() {
            });
            //缓存活动信息
            saveSessionInfo(sesssions);
            //缓存关联商品信息
            saveSessionSkuInfo(sesssions);
        }
    }

    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {

        long time = System.currentTimeMillis();

        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys){
            //seckill:sessions: 1582250400000_1582254000000
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] split = replace.split("_");
            long start = Long.parseLong(split[0]);
            long end = Long.parseLong(split[1]);

            if (time >= start && time <= end){
                //找到场次，获取这个key的所有商品
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);

                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = ops.multiGet(range);

                if (list != null){
                    List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                        SecKillSkuRedisTo redis = JSON.parseObject(item, SecKillSkuRedisTo.class);
                        return redis;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }
        return null;
    }

    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();

        if (keys != null && keys.size() > 0){
            //使用正则匹配
            String regx = "\\d_" + skuId;

            for (String key : keys) {
                if (Pattern.matches(regx,key)){
                    String s = ops.get(key);
                    SecKillSkuRedisTo secKillSkuRedisTo = JSON.parseObject(s, SecKillSkuRedisTo.class);

                    //秒杀没开始不返回随机码
                    long time = System.currentTimeMillis();
                    if (time < secKillSkuRedisTo.getStartTime()){
                        secKillSkuRedisTo.setRandomCode(null);
                    }

                    return secKillSkuRedisTo;
                }
            }
        }
        return null;
    }

    /**
     * 秒杀
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {

        long s1 = System.currentTimeMillis();
        //1、登录判断，拦截器帮我们做了
        //2、合法性校验
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = ops.get(killId);

        if (StringUtils.isEmpty(s)) return null;
        SecKillSkuRedisTo skuRedisTo = JSON.parseObject(s, SecKillSkuRedisTo.class);

        //校验秒杀时间
        Long current = System.currentTimeMillis();
        Long startTime = skuRedisTo.getStartTime();
        Long endTime = skuRedisTo.getEndTime();
        if (current < startTime || current > endTime) return null;

        //校验随机码 和 skuId
        String randomCode = skuRedisTo.getRandomCode();
        Long skuId = skuRedisTo.getSkuId();
        Long promotionSessionId = skuRedisTo.getPromotionSessionId();
        String redisKey = promotionSessionId + "_" + skuId;
        if (!randomCode.equals(key) || !redisKey.equals(killId)) return null;

        //校验秒杀数量
        Integer limit = skuRedisTo.getSeckillLimit();
        if (num > limit) return null;

        //校验是否已经买过，幂等性校验
        MemberRespVo member = LoginUserInterceptor.loginUser.get();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(member.getId() + "_" + redisKey, num.toString(), endTime - startTime, TimeUnit.MILLISECONDS);
        if (!flag) return null;

        //信号量扣减
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
        try {
            semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
            String timeId = IdWorker.getTimeId();

            //发消息给MQ
            SeckillOrderTo orderTo = new SeckillOrderTo();
            orderTo.setOrderSn(timeId);
            orderTo.setMemberId(member.getId());
            orderTo.setNum(num);
            orderTo.setPromotionSessionId(promotionSessionId);
            orderTo.setSkuId(skuId);
            orderTo.setSeckillPrice(skuRedisTo.getSeckillPrice());
            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
            long s2 = System.currentTimeMillis();
            log.info("耗时...{}", (s2 - s1));
            return timeId;

        } catch (InterruptedException e) {
            return null;
        }
    }

    //缓存活动信息
    private void saveSessionInfo(List<SeckillSesssionsWithSkus> sesssions){
        if (sesssions != null)
            sesssions.stream().forEach(sesssion -> {
                Long startTime = sesssion.getStartTime().getTime();
                Long endTime = sesssion.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;

                Boolean hasKey = redisTemplate.hasKey(key);
                if (!hasKey) {
                    List<String> collect = sesssion.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    //缓存活动信息
                    redisTemplate.opsForList().leftPushAll(key, collect);
                    //TODO 设置过期时间[已完成]
                    redisTemplate.expireAt(key, new Date(endTime));
                }
            });
    }

    //缓存关联商品信息
    private void saveSessionSkuInfo(List<SeckillSesssionsWithSkus> sesssions){
        if (sesssions != null)
            sesssions.stream().forEach(sesssion -> {
                //准备hash操作
                BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

                sesssion.getRelationSkus().stream().forEach(seckillSkuVo -> {
                    //4、随机码
                    String token = UUID.randomUUID().toString().replace("-", "");

                    if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                        //缓存商品
                        SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();
                        //1、sku的基本数据
                        R skuInfo = productFeignService.info(seckillSkuVo.getSkuId());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            redisTo.setSkuInfo(info);
                        }

                        //2、sku的秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, redisTo);

                        //3、设置上当前商品的秒杀时间信息
                        redisTo.setStartTime(sesssion.getStartTime().getTime());
                        redisTo.setEndTime(sesssion.getEndTime().getTime());

                        redisTo.setRandomCode(token);
                        String jsonString = JSON.toJSONString(redisTo);
                        //TODO 每个商品的过期时间不一样。所以，我们在获取当前商品秒杀信息的时候，做主动删除，代码在 getSkuSeckillInfo 方法里面
                        ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), jsonString);
                        //如果当前这个场次的商品的库存信息已经上架就不需要上架
                        //5、使用库存作为分布式的信号量  限流；
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        //商品可以秒杀的数量作为信号量
                        semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                        //TODO 设置过期时间。
                        semaphore.expireAt(sesssion.getEndTime());
                    }
                });
            });
    }

}
